<template>
  <div class="container">
    <!-- 分类选择器 -->
    <div class="sidebar-container">
      <van-sidebar v-model="activeKey" scrollspy>
        <van-sidebar-item
          v-for="(category, index) in categories"
          :key="index"
          :title="category"
          @click="onMenuClick(index)"
          :badge="
            orderEachClassQuantity[index] > 0
              ? orderEachClassQuantity[index]
              : null
          "
        >
          <template #icon>
            <van-icon name="shopping-cart-o" />
          </template>
        </van-sidebar-item>
      </van-sidebar>
    </div>
    <!-- 商品列表 -->
    <div class="goods-list-container">
      <van-cell-group>
        <!-- 外层循环遍历 filteredItems -->
        <div
          v-for="(itemsGroup, groupIndex) in filteredItems"
          :key="groupIndex"
        >
          <div
            style="display: flex; justify-content: center; align-items: center"
          >
            {{ categories[groupIndex] }}
          </div>
          <!-- 内层循环遍历 itemsGroup -->
          <van-card
            v-for="(item, index) in itemsGroup"
            :key="index"
            class="custom-card"
            :title="item.name"
            :thumb="item.image"
            :id="`card-${groupIndex}-${index}`"
          >
            <template #desc>
              <span>月售{{ item.monthSales }}</span>
            </template>

            <template #price>
              <!-- 价格显示 -->
              <span>¥{{ item.price }}</span>
              <!-- "+" 按钮 -->
            </template>

            <template #footer>
              <van-button
                v-if="item.tag === 1"
                round
                type="primary"
                size="mini"
                @click="choosePackage"
                >选规格</van-button
              >
              <van-button
                v-else-if="orderDishesQuantity[groupIndex][index] === 0"
                type="primary"
                size="mini"
                icon="plus"
                class="plus-button"
                @click="addDishes(groupIndex, index, item)"
              />
              <van-stepper
                v-else
                v-model="orderDishesQuantity[groupIndex][index]"
                theme="round"
                button-size="22"
                min="0"
                disable-input
                @plus="addDishes(groupIndex, index, item)"
                @minus="decreaseDishes(groupIndex, index, item)"
              />
            </template>
          </van-card>
        </div>
      </van-cell-group>
    </div>
    <!-- 底部操作栏 -->
    <!-- 图标:https://information-system.oss-cn-beijing.aliyuncs.com/86d7021c-b2aa-443d-afbc-f53ff387d3b8.svg -->
    <div v-if="orderDishesAmount > 0">
      <van-action-bar>
        <van-action-bar-icon
          icon="cart-o"
          :badge="orderDishesAmount"
          text="购物车"
        />
        <div class="label-item">
          <span>到手约¥{{ spendMoney }}</span>
          <span>另需配送费¥{{ merchant.deliveryFee }}</span>
        </div>
        <van-action-bar-button
          :color="buttonColor"
          :type="buttonType"
          :text="buttonText"
          :disabled="buttonDisabled"
          @click="goToCheckout"
        />
      </van-action-bar>
    </div>
    <div>
      <!-- 第一个弹出层 -->
      <van-popup
        v-model:show="showSubmit"
        closeable
        position="bottom"
        :style="{ height: '90%' }"
      >
        <template #default>
          <div>
            <div>
              <!-- 单元格 -->
              <van-cell-group style="padding-top: 10%">
                <div>
                  <van-cell size="large" inset="true" @click="toChooseAddress">
                    <template #title>
                      <span
                        v-if="deliveryAddress === null"
                        style="color: rgb(234, 98, 64); font-weight: bold"
                      >
                        请选择收货地址
                      </span>
                      <van-cell v-else>
                        <template #title>
                          <h3>
                            {{ deliveryAddress.deliveryAddress }}
                          </h3>
                        </template>
                        <template #label>
                          <div class="address-detail-container">
                            <span>
                              <span>
                                {{ deliveryAddress.contactName }}
                                {{
                                  deliveryAddress.sex === 1 ? "先生" : "女士"
                                }}
                              </span>
                              {{ deliveryAddress.phoneNumber }}
                            </span>
                          </div>
                        </template>
                      </van-cell>
                    </template>
                  </van-cell>
                </div>

                <van-radio-group v-model="selectedDeliveryTime">
                  <van-cell>
                    <template #title>
                      <span>立即配送</span>
                    </template>
                    <template #right-icon>
                      <van-radio name="immediate" />
                    </template>
                  </van-cell>
                  <van-cell>
                    <template #title>
                      <span>预约配送</span>
                    </template>
                    <template #right-icon>
                      <van-radio name="scheduled" />
                    </template>
                  </van-cell>
                </van-radio-group>
              </van-cell-group>
              <!-- 商品列表 :从购物车中获取,或者直接从orderDishesQuantity判断，-->
              <div
                v-for="(itemsGroup, groupIndex) in filteredItems"
                :key="groupIndex"
              >
                <div v-for="(item, index) in itemsGroup" :key="index">
                  <van-card
                    v-if="orderDishesQuantity[groupIndex][index] > 0"
                    class="custom-card"
                    :title="item.name"
                    :thumb="item.image"
                    :id="`card-${groupIndex}-${index}`"
                  >
                    <template #desc>
                      <span style="color: silver"
                        >超好吃的一道菜,不好吃找我补...</span
                      >
                    </template>

                    <template #price>
                      <!-- 价格显示 -->
                      <span
                        >¥{{
                          item.price * orderDishesQuantity[groupIndex][index]
                        }}</span
                      >
                      <!-- "+" 按钮 -->
                    </template>
                    <template #num>
                      <span
                        ><span>&times;</span
                        >{{ orderDishesQuantity[groupIndex][index] }}</span
                      >
                    </template>
                  </van-card>
                </div>
              </div>
              <!-- 打包费等描述 -->
              <van-cell-group>
                <van-cell title="打包费">
                  <template #value> &yen;{{ needPackageFee }} </template>
                </van-cell>
                <van-cell title="用户配送费" label="不免费">
                  <template #value> &yen;{{ merchant.deliveryFee }} </template>
                </van-cell>
                <van-cell title="美团红包" is-link @click="toChooseTicky">
                  <template #value> 暂无可用 </template>
                </van-cell>
                <van-cell title="商家代金券" is-link value="暂无可用" />
                <van-cell>
                  <template #title>
                    <h3>总计</h3>
                  </template>
                  <template #value>
                    <h3>
                      &yen;{{
                        spendMoney + needPackageFee + merchant.deliveryFee
                      }}
                    </h3>
                  </template>
                </van-cell>
                <van-cell />
                <van-cell />
                <van-cell />
              </van-cell-group>
            </div>
            <!-- 底部订单栏 -->
            <van-submit-bar
              :price="
                (spendMoney + needPackageFee + merchant.deliveryFee) * 100
              "
              button-text="提交订单"
              @submit="onSubmit"
            />
            <!-- 内嵌一个弹出框:第二个弹出层:选择收货地址 -->
            <div>
              <van-popup
                v-model:show="showAddress"
                closeable
                position="bottom"
                :style="{ height: '60%' }"
              >
                <div class="address-list">
                  <div
                    v-for="(address, index) in addresses"
                    :key="index"
                    class="address-item"
                  >
                    <van-radio
                      v-model="selectedAddress"
                      :name="address.addressId"
                      @click="selectAddress(address)"
                    >
                      <van-cell>
                        <template #title>
                          <h3>
                            {{ address.deliveryAddress }}
                          </h3>
                        </template>
                        <template #label>
                          <div class="address-detail-container">
                            <span>
                              {{ address.contactName }}
                              {{ address.sex === 1 ? "先生" : "女士" }}
                              {{ address.phoneNumber }}
                            </span>
                            <!-- 编辑按钮 -->
                            <span>
                              <van-icon
                                @click.stop="editAddress(address)"
                                name="edit"
                            /></span>
                            <!-- 删除按钮 -->
                            <span>
                              <van-icon
                                @click.stop="deleteAddress(address)"
                                name="delete"
                              />
                            </span>
                          </div>
                        </template>
                      </van-cell>
                    </van-radio>
                  </div>
                  <van-sticky position="bottom" :offset-bottom="15">
                    <div class="add-address">
                      <van-button round type="primary" @click="addAddress">
                        新增收货地址
                      </van-button>
                      <van-popup
                        v-model:show="showAddDeliveryAddressDialog"
                        position="bottom"
                        closeable
                        :style="{ height: '100%' }"
                      >
                        <div id="新增收货地址的组件">
                          <van-field
                            v-model="addressForm.deliveryAddress"
                            label="收货地址"
                            placeholder="例理工大学18栋宿舍"
                            maxlength="100"
                          />
                          <van-field
                            v-model="addressForm.doorPlate"
                            label="门牌号"
                            placeholder="详细地址,例1层101室1"
                            maxlength="20"
                          />

                          <van-field
                            v-model="addressForm.contactName"
                            label="联系人"
                            placeholder="请填写收货人的姓名"
                            maxlength="20"
                          >
                            <template #button>
                              <van-radio-group
                                v-model="addressForm.sex"
                                direction="horizontal"
                              >
                                <van-radio name="1">先生</van-radio>
                                <van-radio name="0">女士 </van-radio>
                              </van-radio-group>
                            </template>
                          </van-field>

                          <van-field
                            v-model="addressForm.phoneNumber"
                            label="手机号"
                            placeholder="请填写收货手机号码"
                            maxlength="11"
                          />
                          <div class="label-radio-group">
                            <van-radio-group
                              v-model="addressForm.tag"
                              direction="horizontal"
                            >
                              <van-radio name="家" label="家">家</van-radio>
                              <van-radio name="公司" label="公司"
                                >公司</van-radio
                              >
                              <van-radio name="学校" label="学校"
                                >学校</van-radio
                              >
                              <van-radio name="父母家" label="父母家"
                                >父母家</van-radio
                              >
                            </van-radio-group>
                          </div>
                          <van-button
                            v-if="saveButtonOrUpdateButton"
                            type="primary"
                            block
                            @click="saveAddress"
                            >确认保存地址</van-button
                          >
                          <van-button
                            v-else
                            type="success"
                            block
                            @click="updateAddress(address)"
                            >确认修改修改地址</van-button
                          >
                        </div>
                      </van-popup>
                      <van-button
                        round
                        type="success"
                        @click="confirmDeliveryAddress"
                      >
                        使用当前地址
                      </van-button>
                    </div>
                  </van-sticky>
                </div>
                <!-- 收货地址选择 -->
              </van-popup>
            </div>
          </div>
        </template>
      </van-popup>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from "vue";
import http from "../../../utils/http"; //导入异步交互的工件
import { useRoute, useRouter } from "vue-router"; //导入接受路由参数的实例
import { showToast, showNotify, Notify, showConfirmDialog } from "vant"; //导入vantUi的相关依赖
const route = useRoute();
const router = useRouter();
//变量区域
//关于用户红包
const toChooseTicky = () => {};
//1.拿取父组件传递过来的商家id
const merchantId = route.query.merchantId; //获取商家id
const showSubmit = ref(false); //控制第一个弹出框提交订单是否出现
const showAddress = ref(false); //控制第二个弹出框选择收货地址的弹出层

const onSubmit = () => {
  showToast("点击按钮提交订单的按钮");
  //如果点击提交订单的按钮
  if (deliveryAddress.value === null) {
    //如果还没有选择收货地址，自动跳到选择页面
    showAddress.value = true;
  } else {
    //发送订单添加请求
    sendAddOrderRequest();
  }
};
const deliveryAddress = ref(null);
const selected = ref(true);
const selectedDeliveryTime = ref("immediate"); // 选择立即配送还是预约配送
//收获地址测试
const confirmDeliveryAddress = () => {
  if (deliveryAddress.value === null) {
    showNotify({ type: "warning", message: "请选择收货地址", duration: 1000 });
  } else {
    //1.关闭地址选择的弹出层
    showAddress.value = false;
    //2.更新收货地址
  }
  //点击确认收获地址的事件
};
const selectedAddress = ref(null); //记录是否已经选择了收货地址
const addresses = ref(); //用户的收货地址

const selectAddress = (address) => {
  //1.收货地址被选中
  selectedAddress.value = address.addressId;
  //2.更新收货地址
  deliveryAddress.value = address;
};
// 编辑地址的逻辑:服用添加收货地址的弹出框
const editAddress = (address) => {
  //1.先赋值作为还原
  addressForm.addressId = address.addressId;
  addressForm.contactName = address.contactName;
  addressForm.deliveryAddress = address.deliveryAddress;
  addressForm.doorPlate = address.doorPlate;
  addressForm.phoneNumber = address.phoneNumber;
  addressForm.sex = address.sex;
  console.log("性别6677为", addressForm.sex);
  addressForm.tag = address.tag;
  //2.将按钮变为修改
  saveButtonOrUpdateButton.value = false;
  //2.弹出修改地址的对话框
  showAddDeliveryAddressDialog.value = true;
  //3.如果确认修改则发送修改请求，并且将addressForm还原

  console.log("编辑地址", address);
};
const saveButtonOrUpdateButton = ref(true); //展示修改收货地址，还是展示增加收货地址的按钮
//修改收货地址的请求

//当点击确认修改地址的按钮后:发送修改请求
const updateAddress = async () => {
  console.log("传递的数据为", addressForm);
  try {
    console.log("执行函数");
    const response = await http.put("user/updateAddress", addressForm);
    if (response.data.msg === "success") {
      showNotify({
        type: "success",
        message: "修改成功",
        duration: 1000,
      });
      showAddDeliveryAddressDialog.value = false; //同样关闭增加地址的窗口
      for (let key in addressForm) {
        //将刚刚调出的内容清空
        if (addressForm.hasOwnProperty(key)) {
          addressForm[key] = null;
        }
      }
      getUserAddresses(); //再次请求刷新收货地址
    } else {
      showNotify({
        type: "danger",
        message: "修改失败",
        duration: 1000,
      });
    }
  } catch {}
};
//删除收获地址的事件
//发送删除请求
const sendDeleteRequest = async (address) => {
  try {
    console.log("执行函数");
    const response = await http.delete("user/deleteAddress", {
      params: {
        addressId: address.addressId,
      },
    });
    if (response.data.msg === "success") {
      showNotify({
        type: "success",
        message: "删除成功",
        duration: 1000,
      });
      getUserAddresses();
    } else {
      showNotify({
        type: "danger",
        message: "删除失败",
        duration: 1000,
      });
    }
  } catch {}
};
//当删除按钮被点击时
const deleteAddress = (address) => {
  showConfirmDialog({
    title: "删除",
    message: "是否确认删除该收货地址",
  })
    .then(() => {
      console.log("执行删除");
      sendDeleteRequest(address);
    })
    .catch(() => {
      // on cancel
    });
};

const showAddDeliveryAddressDialog = ref(false); //控制新增收货地址的对话框时候显示
//收货地址的各个属性
const addressForm = reactive({
  addressId: null,
  sex: null, // 选择男士还是女士的单选框
  tag: null, // 选择的标签,如学校，家里
  doorPlate: null, // 地址详情，如门牌号
  deliveryAddress: null, // 收货地址
  contactName: null, // 联系人
  phoneNumber: null, // 联系电话
  userId: null,
});
// 定义购物车项的接口
interface ShoppingCartItem {
  dishes: Object;
  num: Number;
}
// 创建一个响应式的购物车数组，包含多个购物车项
// const shoppingCarts = reactive<Array<ShoppingCartItem>>([]);
const shoppingCarts = ref();
//当点击新增收货地址以后
const addAddress = () => {
  // 新增地址的逻辑
  console.log("新增地址", addressForm);
  saveButtonOrUpdateButton.value = true; //将按钮变为保存
  showAddDeliveryAddressDialog.value = true;
  // router.push("/addAddress");
};
//确认新曾收货地址后，进行处理
const saveAddress = async () => {
  console.log("保存收货地址");
  addressForm.userId = localStorage.getItem("userId"); //将用户id带上
  try {
    const response = await http.post("user/addAddress", addressForm);
    getUserAddresses(); //刷新收货地址
    if (response.data.msg === "success") {
      showNotify({
        type: "success",
        message: "新增收货地址成功",
        duration: 1000,
      });
      // 使用 setTimeout 等待通知消息结束后再关闭对话框
      setTimeout(() => {
        showAddDeliveryAddressDialog.value = false; // 关闭添加收货地址的对话框
      }, 1000); // 延迟时间与通知消息的 duration 相同
    }
  } catch {
    showNotify({ type: "warning", message: "添加失败", duration: 1000 });
  }
  //保存收货地址的逻辑
};
//收获地址测试结束

//2.单独取出parentData方便操作
const parentData = ref(null);
//3.激活的分类键:当前选中的分类的索引
const activeKey = ref(0);
//4.菜品的全部分类
const categories = ref();

//5.相同的菜品分类放在一块展示:即根据activeKey过滤菜品
const filteredItems = ref();

//6.存放所有的菜品
interface Item {
  id: number;
  name: string;
  dishesClass: Array<string>;
  dishesDetails: Object;
  image: string;
  price: number; // 使用 number 而不是 Float32Array
  packFee: number;
  businessId: number;
  monthSales: number;
}
const items = ref<Item[]>([]);
//7.下单的菜品总数量:主要标记是否显示底部的购物车
const orderDishesAmount = ref(0);
//8.存放某一个菜品的点菜的总数量
const orderDishesQuantity = reactive(
  Array(50)
    .fill(0)
    .map(() => Array(50).fill(0))
);
//9.存放每一类菜品的下单数量
const orderEachClassQuantity = reactive(new Array(50).fill(0));
//10.实时计算当前需要的花销:可以判断是否达到商家的起送费
const spendMoney = ref(0);

// 定义计算属性
//11.起送费
const needMoney = ref(15);
//12. 计算按钮颜色
const buttonColor = computed(() =>
  spendMoney.value >= needMoney.value ? "#00BFFF" : "#999999"
);

// 13.计算按钮类型
const buttonType = computed(() =>
  spendMoney.value >= needMoney.value ? "danger" : ""
);

//14. 计算按钮文本
const buttonText = computed(() => {
  if (spendMoney.value >= needMoney.value) {
    return "去结算";
  } else {
    return `差¥${needMoney.value - spendMoney.value}起送`;
  }
});

// 15.计算按钮是否禁用
const buttonDisabled = computed(() => spendMoney.value < needMoney.value);
//16.商家信息
const merchant = ref();
//17.菜品总共的打包费
const needPackageFee = ref(0);

//方法区
//1.根据商家的id获取商家的菜品
const getDishesListById = async () => {
  try {
    const response = await http.get(
      `/dishes/getDishesByBusinessId/${merchantId}`
    );
    items.value = response.data.data; //访问菜品1
    parentData.value = response.data.data; //访问菜品2
  } catch {
    console.error("菜品请求错误");
  }
};
//2.钩子方法:页面挂载的时候调用
onMounted(() => {
  Promise.all([
    getDishesListById(),
    getBusinessInfoById(),
    getShoppingCartByUserIdAndBusinessId(),
  ])
    .then(() => {
      categories.value = getDishesClass();
      filteredItems.value = getClassDishes();
      shoppingCarts.value.forEach((cart) => {
        //1.先根据菜品id从菜品列表中拿到cart.dishesId对应的菜品
        for (const item of parentData.value) {
          if (item.dishesId === cart.dishesId) {
            //找到了菜品
            orderDishesAmount.value += cart.quantity; //1.总共点的菜品数量(包含重复的)
            spendMoney.value += item.price; //2.单纯点菜的总花销
            needPackageFee.value += item.packFee; //3.菜品需要的总打包费
            break;
          }
        }
        //2.对于每一条购物车的记录，再根据filteredItems对购物车的菜品进行匹配
        let found = false;
        for (let i = 0; i < filteredItems.value.length; i++) {
          //第一维
          const subArray = filteredItems.value[i]; //取出第二维的长度
          for (let j = 0; j < subArray.length; j++) {
            const item = subArray[j];
            // 与购物车中的项进行匹配
            if (item.dishesId === cart.dishesId) {
              orderDishesQuantity[i][j] += cart.quantity; //当前菜品点了多少
              orderEachClassQuantity[i] += cart.quantity; //每一个分类的点菜数量
              // 跳出外层循环
              found = true;
              break;
            }
          }
          // 如果已经找到目标项并跳出了内层循环，可能不需要继续检查后续的嵌套数组
          if (found) {
            break;
          }
        }
      });
    })
    .catch((error) => {
      console.error("请求失败", error);
    });
  getUserAddresses(); //挂载的时候就可以获取收货地址了
});
//3.左边的菜单被点击事件:进行页面的滚动
const scrollToCategoryDish = (groupIndex) => {
  const firstDishOfCategory = filteredItems.value[groupIndex][0];

  // 确保 firstDishOfCategory 是有效的
  if (firstDishOfCategory) {
    const dishElement = document.getElementById(`card-${groupIndex}-0`);
    // 如果找到了对应的菜品元素，则平滑滚动到该元素
    if (dishElement) {
      // 假设你想要距离顶部100像素
      const offsetTop = "center";
      dishElement.scrollIntoView({
        behavior: "smooth",
        block: offsetTop,
      });
    } else {
      console.log("滚动函数中没有获取到该元素");
    }
  }
};
//4.点击加菜
const addDishes = (groupIndex, index, item) => {
  //首先更新当前页面
  orderDishesQuantity[groupIndex][index]++; //每一个菜品点了多少
  orderEachClassQuantity[groupIndex]++; //每一个分类的点菜数量
  orderDishesAmount.value++; //点菜的总数量
  spendMoney.value += item.price; //菜品的总价
  needPackageFee.value += item.packFee; //菜品需要的总打包费
  let f = false; //当前菜品的id是否在购物车里面出现过
  //1.遍历整个购物车:检查当前添加的菜品是否已经在购物车里面
  for (const cart of shoppingCarts.value) {
    // console.log("遍历的购物车菜品id为", cart.dishesId);
    if (cart.dishesId === item.dishesId) {
      f = true; //已经出现过了
      sendUpdateShoppingCartRequest(groupIndex, index, item); //对当前记录对应的菜品更新数量
      break;
    }
  }
  //2.如果找完整个购物车，也没有该菜品item的信息,则执行添加菜品的操作
  if (!f) {
    sendAddShoppingCartRequest(groupIndex, index, item); //添加购物车记录
  }
  getShoppingCartByUserIdAndBusinessId(); //刷新购物车
  //2.原来已经点击过,在购物车那里该菜品的数量多1
};
//5.点击减菜
const decreaseDishes = (groupIndex, index, item) => {
  //首先更新当前页面
  orderDishesQuantity[groupIndex][index]--;
  orderEachClassQuantity[groupIndex]--;
  orderDishesAmount.value--;
  spendMoney.value -= item.price;
  needPackageFee.value -= item.packFee; //菜品需要的总打包费
  //1.该商品一定在购物车里面
  //1.如果当前的菜品的数量为1,则删掉其在购物车的记录
  for (const cart of shoppingCarts.value) {
    if (cart.dishesId === item.dishesId) {
      if (cart.quantity === 1) {
        sendDeleteShoppingCartRequest(groupIndex, index, item); //删除购物车记录
      } else {
        sendUpdateShoppingCartRequest(groupIndex, index, item); //对当前记录对应的菜品更新数量,少1
      }
      getShoppingCartByUserIdAndBusinessId(); //刷新购物车
      break;
    }
  }
  //2.如果当前菜品的数量大于1,则将购物车记录中的数量减少1
};
//6.点击选规格:待实现
const choosePackage = () => {};
//7.点击去结算的事件
const goToCheckout = () => {
  console.log("结算按钮被点击");
  showSubmit.value = true; //控制第一个弹出框是否出现
};
//8.窗口滚动事件
const onMenuClick = (index) => {
  scrollToCategoryDish(index);
};
//9.计算菜品的全部分类
const getDishesClass = () => {
  const dishesClass = new Set(); // 临时变量：存放总的菜品分类
  // console.log("此时数据为", parentData.value);
  parentData.value.forEach((item) => {
    // 使用不同的变量名来避免混淆
    // 对于每个菜品
    item.dishesClass.forEach((className) => {
      // 使用不同的变量名来避免混淆
      // 遍历其中的dishesClass, 存放进总的分类的集合
      dishesClass.add(className);
    });
  });
  return Array.from(dishesClass); // 将 Set 转换为数组并且返回
};
//10.计算菜品的分类组表:每个分类有哪些菜品
const getClassDishes = () => {
  const sortedItems = [];
  //遍历所有的分类，找到对应的菜品

  categories.value.forEach((dishesClassName) => {
    sortedItems.push(
      items.value.filter((item) =>
        item.dishesClass.some((classInItem) => classInItem === dishesClassName)
      )
    );
  });
  return sortedItems;
};
//11.根据上商家id查询商家的信息
const getBusinessInfoById = async () => {
  try {
    const response = await http.get(`/business/getBusinessById/${merchantId}`);
    merchant.value = response.data.data; //给商家信息赋值
    needMoney.value = merchant.value.minimumDeliveryFee; //给起送费复制
  } catch (error) {
    console.error("商家信息请求错误");
  }
};
//12.收获地址被点击事件
const toChooseAddress = () => {
  showAddress.value = true;
};
//13.获取用户的收货地址
const getUserAddresses = async () => {
  try {
    const response = await http.get("/user/getUserAddresses", {
      params: {
        userId: localStorage.getItem("userId"),
      },
    });
    // console.log("获取到用户的地址", response.data.data);
    addresses.value = response.data.data;
    return response.data.data;
  } catch {
    console.error("收货地址请求失败");
  }
};
//14.查询该用户下，该商家的购物车列表
const getShoppingCartByUserIdAndBusinessId = async () => {
  try {
    const response = await http.get("/shoppingCart/getShoppingCart", {
      params: {
        userId: localStorage.getItem("userId"),
        businessId: merchantId,
      },
    });
    if (response.data.msg === "success") {
      shoppingCarts.value = response.data.data;
    }
  } catch {
    console.error("获取购物失败");
  }
};
//15.发送添加购物车的请求
const sendAddShoppingCartRequest = async (groupIndex, index, item) => {
  try {
    const response = await http.get("/shoppingCart/addShoppingCart", {
      params: {
        userId: localStorage.getItem("userId"),
        businessId: merchantId,
        dishesId: item.dishesId,
        quantity: 1,
      },
    });
    if (response.data.msg === "success") {
    }
  } catch {}
};
//16.发送修改购物车的请求
const sendUpdateShoppingCartRequest = async (groupIndex, index, item) => {
  try {
    const response = await http.get("/shoppingCart/updateQuantity", {
      params: {
        userId: localStorage.getItem("userId"),
        businessId: merchantId,
        dishesId: item.dishesId,
        quantity: orderDishesQuantity[groupIndex][index],
      },
    });
    if (response.data.msg === "success") {
    }
  } catch {}
};
//17.发送删除购物车的请求
const sendDeleteShoppingCartRequest = async (groupIndex, index, item) => {
  try {
    const response = await http.get("/shoppingCart/deleteShoppingCart", {
      params: {
        userId: localStorage.getItem("userId"),
        businessId: merchantId,
        dishesId: item.dishesId,
      },
    });
    if (response.data.msg === "success") {
    }
  } catch {}
};
//18.发送添加订单的请求
const sendAddOrderRequest = async () => {
  try {
    const response = await http.get("/order/addOrder", {
      params: {
        userId: localStorage.getItem("userId"),
        businessId: merchantId,
        price:
          spendMoney.value + needPackageFee.value + merchant.value.deliveryFee,
        shippingAddress: deliveryAddress.value.deliveryAddress,
      },
    });
    if (response.data.msg === "success") {
      showNotify({ type: "success", message: "添加订单成功", duration: 1000 });
      router.push({ path: "/pay", query: { orderId: response.data.data } });
      return response.data.data; //返回订单的id
    } else {
      showNotify({ type: "danger", message: "添加订单失败", duration: 1000 });
      return 0;
    }
  } catch {
    console.error("请求添加订单过程发生错误");
    return 0;
  }
};
</script>
<style scoped>
.container {
  display: flex;
  height: 100vh; /* 设置容器高度为视口高度 */
  overflow: hidden; /* 防止容器内部滚动影响到外部 */
}

.sidebar-container {
  overflow-y: auto; /* 设置垂直方向滚动 */
  height: 80%; /* 设置高度为容器高度 */
}

.goods-list-container {
  flex: 1;
  overflow-y: auto; /* 设置垂直方向滚动 */
  height: 100%; /* 设置高度为容器高度 */
  padding: 10px;
}

van-sidebar-item {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 水平起始对齐 */
}

.goods-list {
  flex: 1;
  padding: 10px;
  width: 75%;
}

.centered-thumb {
  max-width: 100%; /* 防止图片超出卡片宽度 */
  max-height: 100%; /* 防止图片超出卡片高度 */
  object-fit: cover; /* 裁剪图片以适应容器 */
}

.plus-button {
  margin-left: 200px; /* 根据需要调整间距 */
  border-radius: 50%; /* 使按钮变为圆形 */
}
.sidebar-container::-webkit-scrollbar,
.container::-webkit-scrollbar,
.goods-list-container::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.label-item {
  display: flex; /* 启用Flexbox布局 */
  flex-direction: column; /* 垂直排列key和value */

  align-items: flex-start; /* key和value在行内左对齐 */
  margin-bottom: 0px; /* 给每个label-item添加一些底部间距 */
}
/*收货地址相关样式*/
.address-list {
  padding: 16px;
}

.address-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.address-info {
  flex: 1;
}

.address-title {
  font-weight: bold;
}

.address-detail,
.address-contact {
  color: #888;
}

.address-item van-button {
  margin-left: 16px; /* 调整编辑按钮与地址信息的距离 */
}
/*最下方的两个按钮的样式 */
.add-address {
  margin-top: 16px;
  background: white;
  text-align: center;
  display: flex;
  justify-content: space-between;
  align-items: center; /* 垂直居中对齐 */
}
/*编辑地址的样式*/
.address-detail-container {
  display: flex;
  justify-content: space-between;
  align-items: center; /* 垂直居中对齐 */
}
/* 新增收货地址中标签与其余4个单选框之间的样式 */
.label-radio-group {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 水平起始对齐，标签在前，单选按钮组在后 */
  margin-left: 16px; /* 调整左边距 */
  margin-right: 30px; /* 调整元素之间的右边距 */
  margin: 20px;
}
</style>
